<!--
 @description 编辑经销商档案变更 编辑
 @fileName Edit.vue
 @author zengqiongying
 @created 2023-04-26 19:43:01
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData" />

      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
        required
      />

      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="dealerData.officeCode && detail.customerCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>
    <Card>
      <div class="editItem" @click.stop="toEditPage('address')">
        <div class="name">经销商收货地址更改</div>
        <div v-if="addressIsChange" class="color-normal">修改过</div>
        <qmp-icon class="icon" name="arrow" />
      </div>
    </Card>

    <Card>
      <div class="editItem" @click.stop="toEditPage('contacts')">
        <div class="name">经销商联系人更改</div>
        <div v-if="contactsIsChange" class="color-normal">修改过</div>
        <qmp-icon class="icon" name="arrow" />
      </div>
    </Card>

    <!--  <Card>
      <div class="editItem" @click.stop="toEditPage('shop')">
        <div class="name">门店信息更改</div>
        <div class="color-normal">修改过</div>
        <qmp-icon class="icon" name="arrow" />
      </div>
    </Card> -->

    <Card>
      <div class="editItem">
        <div class="name" @click.stop="openSelectedShop">门店变更 <span class="color-normal">选择门店</span></div>
        <div class="color-grey">先选择门店，再变更门店信息与联系人</div>

        <template v-if="!!activeShopCode">
          <div class="shop-title color-normal">{{ activeShopName }}</div>
          <div class="shop-operator">
            <Cell title="门店信息更改" custom @right="toEditPage('shop')">
              <div v-if="shopIsChange" class="color-normal">修改过</div>
            </Cell>

            <Cell title="门店联系人更改" custom @right="toEditPage('shopContacts')">
              <div v-if="shopContactIsChange" class="color-normal">修改过</div>
            </Cell>
          </div>
        </template>
      </div>
    </Card>
    <template v-if="shopList.length > 0">
      <PopSelect
        v-model:show="showPopShop"
        title="请选择需要变更的门店"
        v-model="activeShopCode"
        v-model:label="activeShopName"
        :list="shopList"
        labelName="name"
        valueName="code"
      />
    </template>

    <div class="ctm-content-foot">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave('B')">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave('A')">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import PopSelect from '@/components/PopSelect/index.vue'
  import { detail, getCustomerShop, submitChange } from '@/apis/dealerMarketing/ArchiveChange'
  import { createSave } from '@/apis/ctmCustomerChange'
  import { initFormData } from '@/utils'

  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerArchiveChangeEdit',
    components: { Card, Cell, DealerCell, FieldSelect, PopSelect },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        detail: {},
        formData: {
          code: '', //单据编号
          isOtherReceiveManagerKnow: '',
          receiveManagerCode: '', // 接收客户经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeCode: '',
          receiveManagerTypeName: '',
          submitAnOpinion: ''
        },
        shopList: [],
        showPopShop: false, //是否显示门店选择
        activeShopCode: '',
        activeShopName: ''
      })
      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      // 地址是否更改
      const addressIsChange = computed(() => {
        const list = datas.detail?.addressDTOS || []
        return list.some((v: any) => v.isBefore !== 1)
      })
      // 经销商联系人是否更改
      const contactsIsChange = computed(() => {
        const list = datas.detail?.contactDTOS || []
        return list.some((v: any) => v.contactScope === 1 && v.isBefore !== 1)
      })

      // 门店是否变更
      const shopIsChange = computed(() => {
        const list = datas.detail?.shopDTOS || []
        return list.some((v: any) => v.isChange === 1 && v.code === `${datas.activeShopCode}`)
      })

      // 门店联系人是否变更
      const shopContactIsChange = computed(() => {
        const list = datas.detail?.contactDTOS || []
        return list.some(
          (v: any) => v.isBefore !== 1 && v.contactScope === 3 && v.shopCode === `${datas.activeShopCode}`
        )
      })

      const getDetail = (refresh = false) => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          datas.detail = res.data || {}
          if (refresh) {
            datas.detail.submitAnOpinion = datas.formData.submitAnOpinion || ''
          }
          initFormData(res.data, datas.formData)
          initShopEditDataByShop(datas.detail.shopDTOS)
          getShopList(datas.detail.customerCode)
        })
      }

      const initShopEditDataByShop = (shops: any) => {
        if (!shops || shops.length > 0) {
          const shop = shops[0]
          datas.activeShopCode = shop.code
          datas.activeShopName = shop.name
          return
        }
        if (datas.shopList.length > 0) {
          initShopEditDataByContact()
        }
      }
      const getShopList = (customerCode: string) => {
        getCustomerShop(customerCode).then((res: any) => {
          datas.shopList = res.data || []
          initShopEditDataByContact()
        })
      }
      const initShopEditDataByContact = () => {
        const constacts = datas.detail?.contactDTOS || []
        const shopContacts = constacts.filter((v: any) => v.isBefore === 0 && v.contactScope === 3 && !!v.shopCode)
        if (shopContacts.length > 0 && datas.shopList.length > 0) {
          const code = shopContacts[0].shopCode
          const shop = datas.shopList.find((v: any) => v.code === code)
          datas.activeShopCode = shop.code
          datas.activeShopName = shop.name
        }
      }

      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }
      const onSearchCustomerManager = () => {
        const officeCode = dealerData.value.officeCode
        const customerCode = datas.detail?.customerCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('ArchiveChangeAddSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/customerManager',
          query: {
            name: 'ArchiveChangeAddSetManager',
            office: officeCode,
            customer: customerCode
          }
        })
      }
      const openSelectedShop = () => {
        if (datas.shopList.length === 0) {
          proxy.$toast('暂无店铺数据')
          return
        }
        datas.showPopShop = true
      }

      const onSave = (schedule: string, callback: any) => {
        const data = {
          id: datas.id,
          schedule,
          ...datas.formData
        }
        if (schedule === 'B') {
          if (none.includes(data.isOtherReceiveManagerKnow)) {
            proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
            return
          }
          if ([1, '1'].includes(data.isOtherReceiveManagerKnow)) {
            if (none.includes(data.receiveManagerCode)) {
              proxy.$toast('请选择接收客户经理')
              return
            }
          }
          const isChange =
            addressIsChange.value || contactsIsChange.value || shopIsChange.value || shopContactIsChange.value
          if (!isChange) {
            proxy.$toast('暂无任何数据变更,无需提交')
            return
          }
        }
        const FunctionName = schedule === 'B' ? submitChange : createSave

        FunctionName(data).then(() => {
          proxy.$toast(schedule === 'B' ? '提交成功' : '保存成功')
          proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
          if (callback) {
            callback()
            return
          }
          nextTick(() => {
            $router.goBack()
          })
        })
      }

      const onView = () => {
        onSave('A', () => {
          $router.push({
            path: '/dealerArchiveChange/preview',
            query: {
              id: `${datas.id}`
            }
          })
        })
      }
      const toEditPage = (path: string) => {
        const query: anyObjectModle = {
          id: `${datas.id}`,
          changeCode: `${datas.detail.code}`
        }
        if (['shop', 'shopContacts'].includes(path)) {
          query.shopCode = datas.activeShopCode
        }
        $router.push({
          path: `/dealerArchiveChange/${path}`,
          query
        })
      }
      proxy.$SimpleEvents.registerEvent('refreshCustomerChangeEditInfo', () => {
        getDetail(true)
      })
      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerInfoArchiveChange', 'DealerArchiveChangeDetail'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })
      getDetail()
      return {
        ...toRefs(datas),
        dealerData,
        onSave,
        onView,
        toEditPage,
        onSearchCustomerManager,
        openSelectedShop,
        shopContactIsChange,
        shopIsChange,
        contactsIsChange,
        addressIsChange
      }
    }
  }
</script>
<style lang="less" scoped>
  .editItem {
    padding: 0 16px;
    position: relative;
    display: flex;
    min-height: 42px;
    justify-content: center;
    flex-direction: column;
    .icon {
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
    }
    .name {
      font: var(--font-main-title-strengthen);
      color: var(--texticon-default-strong);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .state {
      margin-top: 2px;
      font: var(--font-main-body);
      color: var(--texticon-color-brand-normal);
    }
  }
  .shop-title {
    margin-top: 16px;
    font: var(--font-main-title-strengthen);
    padding: 6px 0;
  }
  .shop-operator {
    margin: 0 -16px;
  }
</style>
